<template>
  <el-dialog title="查看二维码" :visible.sync="show" v-loading="loading" @closed="handleClose" width="30%">
    <div class="dialog-container">
      <canvas id="QRCode_header" ref="canvas" title="扫描二维码"></canvas>
      <el-button size="mini" type="primary" @click="saveCode">下载二维码</el-button>
    </div>
  </el-dialog>
</template>
<script>
import QRCode from 'qrcode'
export default {
  data() {
    return {
      show: false,
      loading: true,
      width: 300,
      height: 300,
      logo: require('@/assets/img/qrcode.png'),
      darkColor: '#333333',
    }
  },

  mounted() {},
  methods: {
    // 打开弹出层
    open(row) {
      if (this.show) {
        return
      }
      this.rowData = row || null
      this.show = true
      this.showQRCode()
    },
    // 绘制二维码
    showQRCode() {
      this.$nextTick((a) => {
        QRCode.toCanvas(this.$refs.canvas, this.rowData.url, { width: this.width, height: this.height, color: { dark: this.darkColor } }, (error) => {
          if (error) {
            console.log('加载失败！')
            return
          }
          this.setLogo()
        })
      })
    },
    // 绘制logo
    setLogo() {
      let myCanvas = this.$refs.canvas
      let ctx = myCanvas.getContext('2d')
      // 在Canvas画布 添加图片
      let img = new Image()
      img.crossOrigin = 'Anonymous' //解决Canvas.toDataURL 图片跨域问题
      img.src = this.logo
      img.onload = () => {
        //第一个设置的元素，第二三是位置，后面两个是宽和高
        //居中的位置计算为 （二维码宽度-img宽度）/2
        let codeRate = 0.78
        let codeWidth = (this.width * codeRate) / 2
        let codeHeight = (this.height * codeRate) / 2
        ctx.drawImage(img, codeWidth, codeHeight, this.width * (1 - codeRate), this.height * (1 - codeRate))
      }
    },
    // 下载二维码
    saveCode() {
      //下载二维码
      let base64Img = this.$refs.canvas.toDataURL('image/jpg')
      //创建下载标签，然后设置链接和图片名称
      let a = document.createElement('a')
      a.href = base64Img
      a.download = this.rowData.name
      a.click()
      //销毁元素
      a.remove()
    },
    // 关闭弹出层
    handleClose() {
      this.cleanInfo()
      this.loading = false
      this.drawer = false
    },
    // 清除数据
    cleanInfo() {},
  },
}
</script>
<style lang="scss">
.dialog-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.code-container {
  margin-bottom: 30px;
}
</style>
